<template>
  <div id="addEditDialog">
    <el-dialog
      :title="dialogData.type === 'add' ? '新增商品' : '编辑商品'"
      :visible.sync="dialogData.isShow"
      :close-on-click-modal="false"
      :width="formData.canUseRuler ? '60%' : '50%'"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :rules="rules"
          :model="formData"
          label-width="120px"
        >
          <el-form-item label="选择商品:" prop="cardId">
            <el-button
              type="success"
              icon="el-icon-plus"
              :disabled="dialogData.status === 'PUTAWAY'"
              @click="addGoods"
            >
              添加商品
            </el-button>
            <div class="goodsDetail" v-show="isShowGoodsDetail">
              <span class="goodsDetailItem">
                <b>礼品卡名称: </b>{{ formData.cardName || '' }}
              </span>
              <span class="goodsDetailItem">
                <b>卡面额: </b>{{ formData.cardDenomination / 100 || '' }}
              </span>
              <span class="goodsDetailItem">
                <b>有效期: </b>{{ endTime(formData.endTime) }}
              </span>
              <span class="goodsDetailItem">
                <b>适用商品: </b>{{ formData.usableShop || '' }}
              </span>
              <span class="goodsDetailItem">
                <b>库存: </b>{{ formData.stock || 0 }}
              </span>
              <span class="goodsDetailItem">
                <b>商品链接: </b>{{ formData.link || '' }}
              </span>
            </div>
          </el-form-item>
          <el-form-item label="商品图片:" prop="cardPicture">
            <uploadSingImg
              :imgUrl="formData.cardPicture"
              accept=".jpg,.jpeg,.png,.gif"
              :maxSize="1"
              :showDeleteIcon="true"
              @getImgUrl="getConfigImg"
              :disabled="false"
            >
              <template v-slot:imgInfo>
                支持JPG、PNG、GIF图片格式,大小不超过1M
              </template>
            </uploadSingImg>
          </el-form-item>
          <el-form-item label="商品类型:" prop="type">
            <el-select
              size="small"
              v-model="formData.type"
              clearable
              style="width:30%"
              :disabled="dialogData.status === 'PUTAWAY'"
            >
              <el-option
                v-for="(item, index) in goodsTypeList"
                :key="index"
                :label="item.dictLabel"
                :value="item.dictValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所需积分:" prop="point">
            <el-input
              v-model.trim="formData.point"
              type="text"
              style="width:30%"
              maxlength="7"
              @input="validatePoint"
            ></el-input>
          </el-form-item>
          <el-form-item label="使用规则:" prop="canUseRuler">
            <el-radio-group v-model="formData.canUseRuler" size="small">
              <el-radio
                v-for="(item, index) in canUseRuler"
                :key="index"
                :label="item.dictValue"
                >{{ item.dictLabel }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="rule" v-show="formData.canUseRuler">
            <tiny-mce-editor
              ref="tinyMceEditor"
              :editorContent="formData.rule"
            ></tiny-mce-editor>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="dialogData.isShow = false">
          取 消
        </el-button>
        <el-button type="success" @click="confirm('ruleForm')">确认</el-button>
      </span>
    </el-dialog>
    <selectGiftCardDialog
      v-if="selectGiftCardDialogData.isShow"
      :dialog-data="selectGiftCardDialogData"
      @changeGiftCard="changeGiftCard"
    ></selectGiftCardDialog>
  </div>
</template>
<script>
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import selectGiftCardDialog from './selectGiftCardDialog'
import tinyMceEditor from '@common/tinyMceEditor'
import { sysNormalDisable } from '@utils/dictionariesFunc'
import {
  addCommodity,
  commodityDetail,
  editCommodity
} from '@/api/integralExchange/commodityConfig'
export default {
  props: ['dialogData'],
  components: {
    uploadSingImg,
    selectGiftCardDialog,
    tinyMceEditor
  },
  data() {
    var validatePoint = (rule, value, callback) => {
      if (value === '' || value.charAt('0') === '0') {
        callback(new Error('请输入1-9999999之间的数字, 不能出现小数点'))
      } else {
        callback()
      }
    }
    var validateRule = (rule, value, callback) => {
      if (this.formData.canUseRuler && value === '') {
        callback(new Error('请输入正确的使用规则'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        cardName: '', //礼品卡名称
        cardDenomination: '', //卡片面额
        endTime: '', //有效期
        usableShop: '', //适用商品
        stock: '', //库存
        link: '', //商品链接
        cardPicture: '', //商品图片
        type: 'GIFTCARD', //商品类型
        point: '', //所需积分
        canUseRuler: false, //是否使用规则
        rule: '', //规则
        termType: '',
        cardId: '' //模板编号
      },
      goodsTypeList: [],
      canUseRuler: [
        { dictLabel: '关闭', dictValue: false },
        { dictLabel: '开启', dictValue: true }
      ],
      selectGiftCardDialogData: { isShow: false },
      isShowGoodsDetail: false,
      rules: {
        cardId: [{ required: true, message: '请选择商品', trigger: 'change' }],
        cardPicture: [
          { required: true, message: '请上传商品图片', trigger: 'change' }
        ],
        type: [{ required: true, message: '请选择商品类型' }],
        point: [{ required: true, validator: validatePoint }],
        canUseRuler: [{ required: true }],
        rule: [{ required: true, validator: validateRule }]
      }
    }
  },
  async mounted() {
    this.goodsTypeList = await sysNormalDisable('Integral_commodity_type')
    const { id } = this.dialogData
    if (id) {
      this.isShowGoodsDetail = true
      commodityDetail(id, {}, (res) => {
        this.formData = res
        this.formData.point = res.point.toString()
      })
    }
  },
  methods: {
    /* 添加商品 */
    addGoods() {
      this.selectGiftCardDialogData.isShow = true
    },
    /* 上传商品图片 */
    getConfigImg(url) {
      this.formData.cardPicture = url
      this.$refs['ruleForm'].validateField('cardPicture')
    },
    /* 积分只能输入数字 */
    validatePoint(val) {
      this.formData.point = val.replace(/[^\d]/g, '')
    },
    /* 选择礼品卡 */
    changeGiftCard(val) {
      this.isShowGoodsDetail = true
      const {
        cardName,
        price,
        termType,
        termEndAt,
        applicableCommodities,
        inventory,
        goodsShareUrl,
        templateNo
      } = val
      this.formData.cardName = cardName
      this.formData.cardDenomination = price
      this.formData.endTime = termType ? termEndAt : '永久有效'
      this.formData.usableShop = applicableCommodities
      this.formData.stock = inventory
      this.formData.link = goodsShareUrl
      this.formData.termType = termType
      this.formData.cardId = templateNo
      this.$refs['ruleForm'].validateField('cardId')
    },
    /* 确认提交 */
    confirm(formName) {
      const rule = this.$refs['tinyMceEditor'].tinymceEditorContent()
      if (rule === false) return
      this.formData.rule = this.formData.canUseRuler ? rule : ''
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { id } = this.dialogData
          if (!id) {
            const { termType } = this.formData
            if (!termType) this.formData.endTime = '9999-12-31 00:00:00'
            addCommodity(this.formData, () => {
              this.$emit('refresh')
              this.dialogData.isShow = false
            })
          } else {
            editCommodity(id, this.formData, () => {
              this.$message.success('修改成功')
              this.$emit('refresh')
              this.dialogData.isShow = false
            })
          }
        }
      })
    }
  },
  computed: {
    endTime() {
      return function(val) {
        return val.includes('9999') ? '永久有效' : val
      }
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.el-dialog) {
  margin: 1vh auto !important;
}
.goodsDetail {
  padding: 0 10px;
  width: fit-content;
  border: 2px dashed #333;
  .goodsDetailItem {
    display: block;
    margin-right: 20px;
  }
}
</style>
